<template>
  <view class="form-item"
    v-if="field&&['addchildlist','updatechildlist','detailchildlist','detail'].includes(field.use_type)">
    <child-list :config="field" :srvType="formType" :appName="srvApp" :disabled="field&&field.disabled===true"
      :main-data="mainData" ref="childList" @child-list-change="childListChange">
    </child-list>
  </view>
  <view class="form-item" v-else-if="fieldData.display&&showColumn" :class="{
    'section-top':sectionTop,
    'before-section':beforeSection,
		'disabled-field':fieldData.disabled&&pageType !== 'detail',
      'form-detail': pageType === 'detail',
      valid_error: !valid.valid,
      'flex-column': labelPosition === 'top' || label_width === '100%',
    }">
    <label :for="fieldData.column" class="form-item-label" :class="{
        'form-detail': pageType === 'detail',
        valid_error: !valid.valid,
        'label-top': labelPosition === 'top' || label_width === '100%',
      }" :style="{
        width: label_width,
        'align-items': labelAlign ? labelAlign : 'left',
        'background-color': labelPosition === 'left' ? '' : '',
      }" v-if="fieldData.hideLabel!==true">
      <text class="label" :for="fieldData.column">
        <text class="text-red is-required" v-if="fieldData.isRequire&&formType!=='detail'">
          {{
          fieldData.isRequire ? "*" : ""
        }}</text>
        <text class="text-hidden is-required" v-else>*</text>
        <text>{{ fieldData.customLabel|| fieldData.label }}</text>
      </text>
    </label>
    <view class="form-item-content" :class="{
        'form-detail': pageType === 'detail',
        valid_error: !valid.valid,
        'label-top': labelPosition === 'top' || label_width === '100%',
      }">
      <view class="pend-text pre" v-if="fieldData.moreConfig&&fieldData.moreConfig.prependText">
        {{fieldData.moreConfig.prependText}}
      </view>
      <!-- detail-详情-start -->
      <view class="form-item-content_detail form-item_image"
        v-if="pageType === 'detail' && fieldData.type === 'images'">
        <image class="form-item-content_detail image" v-for="(item, index) in imagesUrl" :key="index"
          style="padding: 5upx" lazy-load show-menu-by-longpress @tap="previewImage(item, 'Image')" data-target="Image"
          :src="item"></image>
      </view>
      <view class="flex" style="width: 100%;" v-else-if="['openDocument','FileList'].includes(fieldData.type)">
        <view class="file-item flex align-center" style="width: 100%;" v-for="item in fileList">
          <text class="margin-lr-xs"
            style="flex: 1;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">{{item.src_name||'-'}}</text>
          <button class="cu-btn bg-blue round" @click="toPreview(item)">文件预览</button>
        </view>
      </view>
      <view class="form-item-content_detail textarea" v-else-if="
          pageType === 'detail' &&['textarea'].includes(field.type)
        ">
        <textarea class="textarea" disabled :auto-height="true" :value="fieldData.value"></textarea>
      </view>
      <view class="form-item-content_detail rich-text" v-else-if="
          pageType === 'detail' &&['snote','Note','RichText'].includes(field.type)
        ">
        <mp-html :content="fieldData.value.replace(/\<img/gi, '<img width=100%')" v-if="fieldData.value" />
        <!-- <rich-text :nodes="field.value" class="value rich-text"></rich-text> -->
      </view>

      <view class="form-item-content_detail" v-else-if="fieldData.type==='multiSelectByJson'">
        <text class="cu-tag" v-for="tag in multiSelectJson">
          {{tag['disp_val']}}
        </text>
      </view>
      <view class="form-item-content_detail file-list flex flex-wrap" style="width: 100%;"
        v-else-if="fieldData.type==='FileList'">
        <view class="file-item text-blue   margin-bottom-xs" v-for="item in fileList"
          style="flex:1;overflow: hidden;border-bottom:1px solid;text-overflow: ellipsis;white-space: nowrap;"
          @click="toPreview(item)">
          <text class="cuIcon-file margin-lr-xs"></text>
          <text>{{getFileName(item)||'-'}}</text>
        </view>
      </view>
      <view class="form-item-content_value" v-else-if="pageType === 'detail'  && fieldData.type === 'MultiSelector'">
        <view class="disabled" style="width: 100%;">
          <rudon-multiSelector welcome="请选择" disabled :is_using_slot="false" :is_using_icon="true"
            :localdata="multiSelectorOptions" @change="whenChanged"></rudon-multiSelector>
        </view>
      </view>
      <view class="form-item-content_detail text"  v-else-if="pageType === 'detail' && fieldData.type === 'DateRange'&&DateRangeConfig">
        {{start2end||''}}
      </view>
      <view class="form-item-content_detail text" :class="{ 'can-link': canLink }" v-else-if="pageType === 'detail'"
        @click="toFKLink">
        {{ fkFieldLabel || fieldData.value | formalText }}
      </view>
      <!-- detail-详情-end -->
      <!-- form-item-start -->
      <view class="form-item-content_value" v-else-if="fieldData.type === 'DateRange'&&DateRangeConfig">
        <uni-datetime-picker v-model="dateRange" type="daterange" @change="dateRangeChange" />
      </view>
      <view class="form-item-content_value picker" v-else-if="fieldData.type === 'MultiSelector'">
        <view class="" style="width: 100%;">
          <rudon-multiSelector welcome="请选择" :is_using_slot="false" :is_using_icon="true"
            :localdata="multiSelectorOptions" @change="whenChanged"></rudon-multiSelector>
        </view>
      </view>
      <bx-radio-group class="form-item-content_value radio-group" :mode="subtype" v-model="fieldData.value"
        v-else-if="fieldData.type === 'radio'" @change="radioChange" :disabled="fieldData.disabled">
        <bx-radio :allowCanel="fieldData.moreConfig&&fieldData.moreConfig.allowCanel" class="radio" color="#2979ff"
          v-for="item in fieldData.options" :key="item" :disabled="fieldData.disabled|| false" :name="item">{{ item }}
        </bx-radio>
      </bx-radio-group>
      <bx-radio-group class="form-item-content_value radio-group" :mode="subtype" :disabled="fieldData.disabled"
        v-model="fieldData.value" v-else-if="fieldData.type === 'radioFk'" @change="radioChange">
        <bx-radio :allowCanel="fieldData.moreConfig&&fieldData.moreConfig.allowCanel" :iconSize="fieldData.iconSize"
          class="radio" color="#2979ff" v-for="item in radioOptions" :key="item.value"
          :disabled="fieldData.disabled||false" :name="item.value" :serial-char="item.serialChar">
          {{ item.label }}
        </bx-radio>
      </bx-radio-group>
      <checkbox-group name="checkbox-group" class="form-item-content_value checkbox-group"
        v-else-if="fieldData.type === 'checkbox'" :disabled="fieldData.disabled">
        <label v-for="(item, index) in radioOptions" :key="index" class="checkbox">
          <checkbox color="#2979ff" :value="item" :disabled="fieldData.disabled|| false" :checked="isChecked(item)" />
          <text style="flex: 1" class="text">{{ item }}</text>
        </label>
      </checkbox-group>
      <bx-checkbox-group :mode="subtype" v-model="fieldData.value" class="form-item-content_value checkbox-group"
        v-else-if="fieldData.type === 'checkboxFk'" :disabled="fieldData.disabled || false" @change="onBlur">
        <bx-checkbox v-model="item.checked" v-for="(item,index) in radioOptions" :key="index" :name="item.label">
          {{ item.label }}
        </bx-checkbox>
      </bx-checkbox-group>
      <view class="" v-else-if="fieldData.type==='Set'">
        <bx-checkbox-group class=" form-item-content_value checkbox-group" :mode="subtype" @change="pickerChange">
          <bx-checkbox v-for="item in setOptionList" @change="changeCheckbox"
            @on-change="changeCheckbox($event,item.value)" @input="changeCheckbox($event,item.value)" :key="item.value"
            :name="item.value" v-model="item.checked">
            {{ item.label }}
          </bx-checkbox>
        </bx-checkbox-group>
      </view>
      <uni-data-select v-else-if="fieldData.type=='Radio' &&subtype==='select'" :value=" fieldData.value"
        :localdata="radioOptions" @change="onSelectChange" @clear="clearSelectValue">
      </uni-data-select>
      <view class="" v-else-if="fieldData.type === 'Radio'">
        <bx-radio-group class="form-item-content_value radio-group" v-model="fieldData.value"
          :allowCanel="fieldData.moreConfig&&fieldData.moreConfig.allowCanel" :mode="subtype" @change="pickerChange"
          :disabled="fieldData.disabled">
          <bx-radio v-for="item in radioOptions" :key='item.value' :name="item.value">{{ item.label }}
          </bx-radio>
        </bx-radio-group>
      </view>
      <view class="form-item-content_value picker" v-else-if="fieldData.type==='TreeSelector'">
        <uni-data-picker :allow-select-branch="true" v-model="fieldData.value" :border="false"
          :localdata="localTreedata" :map='treeMap' popup-title="请选择" @change="onTreeChange"
          @nodeclick="onTreeNodeClick"></uni-data-picker>
      </view>

      <view class="form-item-content_value picker" v-else-if="popupFieldTypeList.includes(fieldData.type)">
        <uni-data-select v-if="fieldData.col_type == 'Enum'||fieldData.type === 'Selector'" v-model="fieldData.value"
          :localdata="radioOptions" @change="onSelectChange" @clear="fieldData.value=''"></uni-data-select>
        <!-- 			<select-lazy v-else-if="fieldData.type === 'Selector'" :zindex="10" :value="fieldData.value"
					:name="fieldData.columns" :placeholder="placeHolder" :options="radioOptions" @selectitem="selectItem">
				</select-lazy> -->
        <view class="selector-tip"
          v-else-if="selectorData.length===0&&setOptionList.length===0&&!fkFieldLabel&&!fieldData.value"
          @click="openModal(fieldData.type)">
          请选择
          <text class="cuIcon-right "></text>
        </view>
        <view class="" v-else-if="selectorData.length===0&&fkFieldLabel" @click="openModal(fieldData.type)">
          {{fkFieldLabel||fieldData.value||'请选择'}}
          <text class="cuIcon-right margin-left-xs"></text>
        </view>
        <view class="selector-tip"
          v-else-if="fieldData.type === 'Selector'&&fieldData.moreConfig&&fieldData.moreConfig.editor_type==='selectorList'"
          @click.stop="openModal">
          {{fkFieldLabel||fieldData.value||'请选择'}}
          <text class="cuIcon-right "></text>
        </view>
        <view @click="openModal(fieldData.type)" class="place-holder" v-else-if="
            (fieldData.type === 'Set') ||
            (fieldData.type === 'Selector'&&fieldData.bx_col_type!=='fk')
          ">
          <view class="" v-if="!fieldData.value">
            <text>{{!fieldData.disabled?'请选择':''}}</text>
            <text class="cuIcon-right" v-if="!fieldData.disabled"></text>
          </view>
          <view class="value hidden" v-else-if="fieldData.type==='multiSelectByJson'">
            <text class="cu-tag" v-for="tag in multiSelectJson">
              {{tag['disp_val']}}
            </text>
          </view>
          <view class="value hidden" v-else-if="fieldData.value && isArray(fieldData.value)">
            {{ fieldData.value.toString() }}
          </view>
          <text class="value hidden" v-else-if="fkFieldLabel">{{
					  fkFieldLabel|| ""
					}}</text>
          <view class="value hidden" v-else-if="fieldData.value">{{
            fieldData.value
          }}</view>
          <text class="cuIcon-right" v-if="fieldData.value&&!fieldData.disabled"></text>
        </view>
        <view class="selector-tip flex align-center" v-else @click="openModal(fieldData.type)">
          <text class="place-holder" v-if="!fieldData.value"> 请选择</text>
          <text v-else> {{fkFieldLabel||fieldData.value}}</text>
          <text class="cuIcon-right "></text>
        </view>
      </view>

      <view class="form-item-content_value"
        v-else-if="fieldData&&fieldData.moreConfig&&fieldData.moreConfig.editor_type&&fieldData.moreConfig.editor_type==='date_range_picker_ck'&&fieldData.column===fieldData.moreConfig.start_col">
        <ck-date-range-picker ref="ckPicker" :service-no="serviceNo" @confirm="confirmPicker" v-if="serviceNo">
          <view class="flex">
            <view class="" v-if="start&&end">
              {{start|formatDate}} - {{end|formatDate}}
            </view>
            <view class="" v-else>
              请选择
            </view>
            <text class="cuIcon-right margin-left-xs"></text>
          </view>
        </ck-date-range-picker>
      </view>
      <view class="form-item-content_value picker" v-else-if="pickerFieldList.includes(fieldData.type)">
        <date-range-picker style="width: 100%;" :disabled="fieldData.disabled" :field="fieldData" :mode="pickerMode"
          :isRange="pageType==='filter'" :priceConfig="datePriceConfig" :fieldsModel="fieldsModel" :max="max" :min="min"
          v-model="fieldData.value" @change="bindTimeChange">
        </date-range-picker>
      </view>
      <view class="form-item-content_value textarea" v-else-if="fieldData.type === 'textarea'"
        :class="{disabled:fieldData.disabled}">
        <textarea class="textarea-content" :adjust-position="true" :value="fieldData.value" :show-confirm-bar="false"
          :placeholder="fieldData.disabled?'不可编辑':'请输入'" @blur="inputChange" :disabled="fieldData.disabled"></textarea>
      </view>
      <view class="form-item-content_value location" v-else-if="fieldData.type === 'location'" @click="getLocation">
        {{ fkFieldLabel||fieldData.value || "点击选择地理位置" }}
      </view>
      <view class="form-item-content_value location" v-else-if="fieldData.type === 'addr'">
        <uni-easyinput primaryColor='#38C09E' v-model="fieldData.value" :inputBorder="false" @confirm="inputChange"
          :maxlength="max_len" :disabled="fieldData.disabled|| false" placeholder="选择或填写位置" />
      </view>
      <view class="form-item-content_value" v-else-if="fieldData.type === 'RichText'" @click="showModal('RichEditor')">
        <view class="value rich-text" v-if="!fieldData.value">请输入</view>
        <rich-text :nodes="fieldData.value" class="value rich-text" v-else></rich-text>
      </view>

      <input class="flex-1 input" type="text" style="" :placeholder="placeHolder" :value="fieldData.value"
        @blur="inputChange" @confirm="inputChange" :maxlength="max_len" :disabled="fieldData.disabled|| false"
        v-else-if="fieldData.type === 'text'" />
        
      <!-- <uni-easyinput  v-model="fieldData.value" placeholder="" /> -->
      
      <uni-rate v-model="fieldData.value" :readonly="fieldData.disabled" :max="max||5" :allowHalf="allowHalf"
        v-else-if="isRate" />
      <input class="flex-1 input" style="" :value="fieldData.value" @blur="inputChange"
        :placeholder="placeHolder" :type="fieldData.type" :inputmode="fieldData.inputmode " :maxlength="max_len"
        :max="max" :min="min" :disabled="fieldData.disabled || false"
        v-else-if="['number','digit'].includes(fieldData.type)" />

      <bx-media-upload class="form-item-content_value image" :min-ratio="fieldData.minRatio"
        :max-ratio="fieldData.maxRatio" :file-no="fieldData.value" v-model="imagesUrl" :mediaType="fieldData.mediaType"
        :enable-del="fieldData.disabled ? !fieldData.disabled : true"
        :enable-add="fieldData.disabled ? !fieldData.disabled : true" :server-url="uploadUrl" @delete="deleteImage"
        @add="getImagesInfo" :form-data="uploadFormData" :header="reqHeader" :showUploadProgress="true"
        :server-url-delete-image="deleteUrl" :limit="fieldData.fileNum"
        v-else-if="['media','openDocument'].includes(fieldData.type)">
      </bx-media-upload>

      <bx-image-upload :max-count="uploadLimit" :uploadText="placeHolder"
        :open-type="['profile_url','user_image'].includes(fieldData.column)?'chooseAvatar':''"
        :disabled="pageType==='detail'||fieldData.disabled||fieldData.column==='goods_image'" :custom-btn="false"
        :interfaceName="formType" :appName="uploadFormData.app_no" :tableName="uploadFormData.table_name"
        :value="fieldData.value" :index="fieldData.column" :action="uploadUrl" @change="imgChange"
        v-else-if="fieldData.type === 'images'">

      </bx-image-upload>
      <view class="pend-text after" v-if="fieldData.moreConfig&&fieldData.moreConfig.appendText">
        {{fieldData.moreConfig.appendText}}
      </view>
      <text class=" right-icon cuIcon-add margin-right bg-black text-white round"
        v-if="showRightBtn&&fieldData.moreConfig.rightBtn.type==='add'"
        @click="onRightBtn(fieldData.moreConfig.rightBtn)"></text>

      <button class="button light margin-left " v-else-if="showRightBtn"
        @click="onRightBtn(fieldData.moreConfig.rightBtn)">
        <text>{{fieldData.moreConfig.rightBtn.label}}</text>
      </button>
      
      <field-explain v-if="fieldExplain&&fieldExplain.text" :text="fieldExplain.text" :position="fieldExplain.position">
        
      </field-explain>
    <!--  <view class="right-tip" v-if="fieldExplain&&fieldExplain.text">
        <text class="cuIcon-questionfill" v-if="fieldExplain&&fieldExplain.text" @click="changeExplainTip"></text>
        <view class="tip-content" v-if="fieldExplain.text&&showExplainTip">
          <view class="shadow" @click="changeExplainTip">
          </view>
          <view class="text" @click.stop="">
            {{fieldExplain.text}}
          </view>
        </view>
      </view> -->
      <view class="valid_msg" v-show="!valid.valid">{{ valid.msg }}</view>
    </view>
    <view class="icon-area" v-if="(fieldData.type === 'location' || fieldData.type === 'addr')"><text
        class="cuIcon-locationfill text-cyan" @click="getLocation"></text></view>
    <view class="cu-modal bottom-modal" style="z-index: 15;" v-if="modalName === 'RichEditor'"
      :class="{ show: modalName === 'RichEditor' }" @click="hideModal">
      <view class="cu-dialog" @tap.stop="" v-if="modalName === 'RichEditor'">
        <jin-edit :html="textareaValue" @editOk="saveRichText" :res2Url="uploadRes2Url" :form-data="uploadFormData"
          :header="reqHeader" :uploadFileUrl="uploadUrl" ref="richEditor" />
      </view>
    </view>
    <view class="cu-modal bottom-modal" :class="{
        show: modalName === 'Selector' || modalName === 'MultiSelector',
      }" @click="hideModal" @touchmove.prevent.stop=""
      v-if="fieldData&&fieldData.col_type!=='Enum'&&modalName === 'Selector' || modalName === 'MultiSelector'">
      <view class="cu-dialog" @tap.stop="">
        <option-selector ref='optionSelector' :allowAdd="optionSelectorAllowAdd" :has-next="hasNext"
          :modalName="modalName" :show-search="fieldData.showSearch!==false&&modalName === 'Selector'"
          :options="radioOptions" :selectType="selectType" @load-more="nextPage()" @hide="hideModal()"
          @search="searchFKDataWithKey" @refresh="refresh()"
          :allowCanel="fieldData.moreConfig&&fieldData.moreConfig.allowCanel" @toFkAdd="toFkAdd"
          @change="pickerChange($event,'Selector')">
        </option-selector>
      </view>
    </view>

  </view>
</template>

<script>
  import {
    list2tree
  } from '@/common/api/goods.js'
  export default {
    name: 'aFormItem',
    filters: {
      formatDate(val) {
        if (val) {
          let date = new Date(val)
          if (date.getFullYear() === new Date().getFullYear()) {
            return val.replace(date.getFullYear() + '-', '')
          }
        }
        return val
      },
      formalText(val) {
        if (Array.isArray(val)) {
          val = val.toString();
        } else if (typeof val === 'string') {
          val = val;
        } else if (typeof val === 'object') {
          val = JSON.stringify(val);
        } else if (val === 0) {
          val = '0'
        } else if (!val) {
          val = '';
        }
        if (val === 'null') {
          val = '—';
        }
        return val;
      }
    },
    props: {
      serviceNo: {
        type: String,
      },
      field: {
        type: Object,
        required: true
      },
      // label的位置，left-左边，top-上边
      labelPosition: {
        type: String,
        default: 'left'
      },
      // lable字体的对齐方式
      labelAlign: {
        type: String,
        default: ''
      },
      procData: {
        type: Object,
        default () {
          return {};
        }
      },
      fieldsModel: {
        type: Object,
        default () {
          return {};
        }
      },
      formType: {
        type: String,
        default: 'add' //add||update
      },
      pageType: {
        type: String,
        default: 'form' //form||detail
      },
      optionMode: {
        type: String,
        default: 'normal' //选项的样式 normal | button
      },
      srvApp: {
        type: String,
      },
      sectionTop: {
        type: Boolean,
        default: false
      },
      beforeSection: {
        type: Boolean,
        default: false
      },
      mainData: [Object, Boolean]
    },
    computed: {
      start2end(){
        if(Array.isArray(this.dateRange)&&this.dateRange.length===2){
          return `${this.dateRange[0]} 至 ${this.dateRange[1]}`
        }
      },
      DateRangeConfig() {
        if (this.fieldData?.moreConfig?.DateRangeConfig?.DateRangeEndColName) {
          let data = {
            ...this.fieldData.moreConfig.DateRangeConfig

          }
          return data
        }
      },
      showRightBtn() {
        return this.fieldData?.moreConfig?.rightBtn?.inAIO
      },
      allowHalf() {
        return this.fieldData?.moreConfig?.allowHalf || false
      },
      isRate() {
        return ['number', 'digit'].includes(this.fieldData.type) && this.fieldData?.moreConfig?.mode === 'rate'
      },
      placeHolder() {
        if (this.fieldData.type === 'images') {
          if (this.fieldData.column === 'goods_image') {
            return `如需上传商品图片，请登录电脑端上传`
          }
          return `上传${this.fieldData.label}`
        }
        let placeholder = this.fieldData?.placeholder || `请输入${this.fieldData?.customLabel||this.fieldData?.label}`
        if (['Selector'].includes(this.fieldData.type)) {
          placeholder = this.fieldData?.placeholder || `请选择${this.fieldData?.customLabel||this.fieldData?.label}`
        }
        return this.fieldData.disabled === true ? '不可编辑' : placeholder
      },
      subtype() {
        return this.fieldData?.subtype || this.fieldData?._subtype || this.optionMode
      },
      fieldExplain() {
        return {
          text: this.fieldData?.moreConfig?.help_tips,
          position: this.fieldData?.moreConfig?.appExplainPosition|| this.fieldData?.moreConfig?.explainPosition,
          color: this.fieldData?.moreConfig?.explainColor
        }
      },
      // 文件上传最大数量
      uploadLimit() {
        return this.fieldData?.moreConfig?.maxCount || this.fieldData?.limit || 10
      },
      optionSelectorAllowAdd() {
        return this.fieldData?.moreConfig?.allow_add !== false
      },
      // serviceNo() {
      //   return this.mainData?.service_people_no
      // },
      showColumn() {
        let res = true;
        if (this.fieldData?.moreConfig?.editor_type === 'date_range_picker_ck' && this.fieldData?.moreConfig
          ?.end_col === this.fieldData.column) {
          res = false
        }
        return res
      },
      multiSelectJson() {
        let res = []
        if (this.fieldData.type === 'multiSelectByJson') {
          if (Array.isArray(this.fieldData.jsonValue)) {
            res = this.fieldData.jsonValue
          } else if (this.fieldData.value) {
            try {
              res = JSON.parse(this.fieldData.value)
            } catch (e) {
              //TODO handle the exception
            }
          }
        }
        return res.map(item => {
          if (this.fieldData?.fmt?.disp_col) {
            item.disp_val = item[this.fieldData?.fmt?.disp_col]
          }
          return item
        })
      },
      selectType() {
        // 自行输入 下拉选择 编辑选择
        return this.fieldData?.option_list_v2?.select_type
      },
      min() {
        return this.fieldData?.item_type_attr?.min || this.fieldData?.min || this.fieldData?.moreConfig?.min
      },
      max_len() {
        return this.fieldData?.item_type_attr?.max_len || this.fieldData?.max_len || this.fieldData?.moreConfig
          ?.max_len || 999999
      },
      max() {
        return this.fieldData?.item_type_attr?.max || this.fieldData?.max || this.fieldData?.moreConfig?.max
      },
      hasNext() {
        return this.treePageInfo.total > this.treePageInfo.rownumber * this.treePageInfo.pageNo
      },
      theme() {
        return this.$store?.state?.app?.theme
      },
      canLink() {
        if (this.fieldData?.moreConfig?.navType === 'takePhone' && this.fieldData.value) {
          return true
        }

        if (this.fieldData.value && this.fieldData.bx_col_type === 'fk') {
          return true
        }
      },
      radioOptions() {
        let res = []

        if (this.modalName === 'MultiSelector') {
          res = this.setOptionList
        }

        const nextRadio = {
          label: '加载更多',
          value: '加载更多',
          checked: false
        }
        if (Array.isArray(this.fieldData.options)) {
          if (this.pageType === 'filter') {
            if (!this.fieldData.options.find(item => item.value === '全部')) {
              res = [...this.fieldData.options, {
                label: '全部',
                value: '全部',
                checked: this.fieldData.options.find(item => item.checked) ? false : true
              }]
            } else {
              res = this.fieldData.options
            }
          } else {
            res = this.fieldData.options
          }
        } else if (Array.isArray(this.selectorData)) {
          // if(this.treePageInfo.total>this.treePageInfo.rownumber*this.treePageInfo.pageNo){
          // 	 res = [...this.selectorData,nextRadio]
          // }
          res = this.selectorData
        }
        if (Array.isArray(res)) {
          res = res.map(item => {
            if (item.label) {
              item.text = item.label
            }
            return item
          })
        }
        return res
      },
      uploadUrl() {
        return this.$api.upload;
      },
      deleteUrl() {
        return this.$api.deleteFile;
      },
      label_width() {
        let result = '';

        if (this.labelPosition === 'left') {
          result = 'auto';
        }
        if (['images', 'textarea', 'RichText', 'media', 'FileList'].includes(this.fieldData.type)) {
          if (this.pageType === 'detail' && !this.fieldData.value) {

          } else {
            // result = '100%'
          }
        }

        return result;
      },
      pickerMode() {
        if (this.fieldData?.moreConfig?.editor_type == 'date_time_linkage') {
          return 'date_time_linkage'
        }
        let type = this.fieldData.type;
        if (this.pickerFieldList.includes(type)) {
          switch (type) {
            case 'Date':
              type = 'date';
              break;
            case 'Time':
              type = 'time';
              break;
          }
          return type;
        }
      },
      datePriceConfig() {
        return this.fieldData?.moreConfig?.date_price_config
      }
    },
    data() {
      return {
        dateRange: "",
        tval: "",
        datalist: [{
            label: "label1",
            value: "value1"
          },
          {
            label: "label2",
            value: "value2"
          },
          {
            label: "label3",
            value: "value3"
          }
        ],
        showExplainTip: false,
        curNode: "",
        // serviceNo:"",
        treeMap: {
          text: 'label',
          value: "value"
        },
        nodeList: [],
        localTreedata: [],
        showEnumSelect: false,
        curEnumIndex: -1,
        otherNodeVal: "",
        focusTextArea: false,
        checkedList: [],
        fieldData: {},
        fileList: [],
        imagesUrl: [],
        popupFieldTypeList: ['Selector', 'multiSelectByJson'], //点击会弹出popup的字段类型
        // popupFieldTypeList: ['TreeSelector', 'treeSelector', 'Selector', 'multiSelectByJson'], //点击会弹出popup的字段类型
        pickerFieldList: ['date', 'dateTime', 'time', 'Time', 'Date'],
        reqHeader: {
          bx_auth_ticket: uni.getStorageSync('bx_auth_ticket')
        },
        uploadFormData: {
          serviceName: 'srv_bxfile_service',
          interfaceName: 'add',
          app_no: '',
          table_name: '',
          columns: ''
        },
        listModel: {},
        textareaValue: '',
        treePageInfo: {
          total: 0,
          rownumber: 30,
          pageNo: 1
        },
        selectorData: [],
        setOptionList: [],
        fkFieldLabel: '',
        valid: {
          column: this.field.column,
          valid: true,
          msg: '不能为空!'
        },
        longpressTimer: 0,
        modalName: '', //当前显示的modal
        selectorListUUID: "",
        selectTreeData: [],
        start: "",
        end: "",
        multiSelectorOptions: []
      };
    },
    watch: {
      'fieldData.value': {
        deep: true,
        immediate: true,
        handler(newVal, oldVal) {
          if (newVal !== oldVal && oldVal !== undefined) {
            this.fieldData.old_value = oldVal
            if (Array.isArray(newVal) && Array.isArray(oldVal) && newVal.length === oldVal.length && newVal
              .length >
              0) {
              let length = newVal.length;
              let eq = 0
              for (let i = 0; i < length; i++) {
                if (newVal[i] === oldVal[i]) {
                  eq++
                }
              }
              if (length === eq) {
                return
              }
            }
            let srvInfo = this.fieldData.srvInfo || this.fieldData.option_list_v2;
            if (srvInfo?.key_disp_col) {
              if (!this.fieldData.value) {
                this.fkFieldLabel = ''
              }
            }
            let fieldData = this.deepClone(this.fieldData)
            fieldData.value = newVal
            console.log(newVal);
            this.$emit('on-value-change', fieldData);
            this.getDefVal()
          }
        }
      },
      field: {
        deep: true,
        immediate: true,
        handler(newValue, oldValue) {
          if (newValue?.type === 'Selector' && newValue?.value !== oldValue
            ?.value) {
            this.pickerChange(newValue.value, 'Selector')
          }
          if (newValue.type === 'textarea' || newValue.type === 'RichText') {
            this.textareaValue = newValue.value;
          }
          if (['images', 'media'].includes(newValue.type)) {
            console.log(newValue.type);
            this.getDefVal()
          }
          if (newValue?.moreConfig?.DateRangeConfig?.DateRangelabel) {
            newValue.customLabel = newValue?.moreConfig?.DateRangeConfig?.DateRangelabel
            this.dateRange = [newValue.value, this.mainData[newValue?.moreConfig?.DateRangeConfig?.DateRangeEndColName]]
          }
          this.fieldData = newValue;
        }
      }
    },
    methods: {
      whenChanged(data) {
        console.log(data);
        debugger
        if (Array.isArray(data)) {
          this.fieldData.value = data.filter(item => item.is_selected === true).map(item => item.value).toString()
          this.onBlur()
        }
      },
      dateRangeChange(range) {
        if (Array.isArray(range) && range.length > 0) {
          // this.fieldData.value = e[0]
          let column = this.DateRangeConfig?.DateRangeEndColName;
          if (column) {
            this.$emit('date-change', {
              moreConfig: {
                start_col: this.fieldData.column,
                end_col: column
              },
              colData: {
                start: range[0],
                end: range[1]
              }
            })
          }
        }
      },
      changeExplainTip() {
        this.showExplainTip = !this.showExplainTip
      },
      onTreeNodeClick(e = {}) {
        // console.log('onTreeNodeClick', e);
        let data = this.nodeList.find(item => item[this.fieldData.option_list_v2?.refed_col] === e[this.fieldData
          .option_list_v2?.refed_col])
        if (data && data[this.fieldData.option_list_v2?.refed_col]) {
          if (this.fieldData.value !== data[this.fieldData.option_list_v2?.refed_col]) {
            // this.getCascaderValue(data)
          }
        }
      },
      onTreeChange(e) {
        console.log('onTreeChange', e);
        const srvInfo = this.fieldData.option_list_v2
        let selectorData = null
        if (Array.isArray(e?.detail?.value) && e.detail.value.length > 0) {
          selectorData = e.detail.value[e.detail.value.length - 1]
          let data = this.nodeList.find(item => item[this.fieldData.option_list_v2?.refed_col] === selectorData
            .value)
          if (data && data[this.fieldData.option_list_v2?.refed_col]) {
            this.getCascaderValue(data)
          }
        } else {
          this.fieldData.value = '';
          this.fkFieldLabel = ''
        }
      },
      childListChange(e) {
        this.$emit('on-childlist-change', e)
      },
      onRightBtn(btn = {}) {
        if (btn.type == "function" && btn.function) {
          // 函数类型 直接修改当前字段的值
          const fun = eval(btn.function);
          const value = fun();
          if (typeof value === "string" || typeof value === "number") {
            this.fieldData.value = value;
            this.onBlur()
          }
        } else {
          const uuid = uni.$u.guid()
          this.$emit("on-right-button", btn, this.fieldData, uuid);
          uni.$on('on-right-button-finish', (e) => {
            console.log(e);
            if (e?.uuid === uuid) {
              if (this.fieldData.type === 'TreeSelector') {
                this.getTreeData()
              } else {
                this.getDefVal()
              }
            }
            this.$nextTick(function() {
              uni.$off('on-right-button-finish')
            })
          })
        }
      },
      getFileName(e) {
        let str = ''
        if (e?.src_name && e.file_type) {
          str = e.src_name
          // str = e.src_name.split(`.${e.file_type}`)[0]
          // if(str.length>30){
          //   str = str.slice(0,10)+'xxxxxx' +str.slice(str.length-10) + `.${e.file_type}`
          // }
        }
        return str
      },
      toPreview(e) {
        if (e._fileurl && e?.file_type && typeof e?.file_type === 'string') {
          const type = e.file_type.toLowerCase()
          switch (type) {
            case 'jpg':
            case 'png':
              uni.previewImage({
                showmenu: false,
                urls: [e._fileurl]
              })
              break;
            default:
              uni.openDocument({
                filePath: e._fileurl
              })
              break;
          }
        }
      },
      showCKPicker() {
        this.$refs?.ckPicker?.open?.()
      },
      onGetTreeData(e) {
        // 树选择器查到数据
        this.selectorData = e || []
        let srvInfo = this.fieldData.srvInfo || this.fieldData.option_list_v2;
        if (this.fieldData.value && srvInfo?.refed_col) {
          let data = this.selectorData.find(item => item[srvInfo?.refed_col] === this.fieldData.value)
          if (data) {
            this.fkFieldLabel = srvInfo.show_as_pair === true ?
              `${data[ srvInfo.key_disp_col ]}/${data[ srvInfo.refed_col ]}` : data[srvInfo.key_disp_col];
            this.fieldData['colData'] = data;
            this.$emit('setColData', this.fieldData)
          }
        }
      },
      confirmEnum(e) {
        if (Array.isArray(e) && e.length > 0) {
          this.fieldData.value = e[0].value
          this.fkFieldLabel = e[0].label || e[0].value
          this.curEnumIndex = this.fieldData.options.findIndex(item => item.value === e[0].value)
        }
      },
      imgChange(val) {
        this.fieldData.value = val
      },
      selectorInput(e) {
        this.fkFieldLabel = e?.detail?.value;
      },
      toFKLink() {
        // 跳转到fk字段的详情页面
        if (this.fieldData?.moreConfig?.navType == 'takePhone' && this.fieldData.value) {
          uni.makePhoneCall({
            phoneNumber: this.fieldData.value
          })
          return
        }
        let serviceName = this.fieldData?.option_list_v2?.serviceName
        let column = this.fieldData?.option_list_v2?.refed_col
        let app = this.fieldData?.option_list_v2?.srv_app || this.srvApp

        if (serviceName && column && this.fieldData.value) {
          let fieldsCond = [{
            column: column,
            value: this.fieldData.value,
            display: false
          }]

          let url =
            `/publicPages/formPage/formPage?type=detail&serviceName=${serviceName}&fieldsCond=${JSON.stringify(fieldsCond)}`
          if (app) {
            url += `&appName=${app}`
          }
          let pageStack = getCurrentPages()
          if (Array.isArray(pageStack) && pageStack.length > 9) {
            uni.redirectTo({
              url
            })({
              url
            })
          } else {
            uni.navigateTo({
              url
            })
          }

        }
      },
      isChecked(val) {
        if (this.fieldData && this.fieldData.value && this.fieldData.value.indexOf(val) !== -1) {
          return true
        } else {
          return false
        }
      },
      reset() {},
      saveRichText(e) {
        if (e.isSave) {
          if (e.type === 'textarea') {
            this.fieldData.value = this.textareaValue;
          } else {
            if (e.html) {
              this.fieldData.value = e.html;
            }
            this.fieldData.richData = e;
          }
        } else {
          let val = this.fieldData.value ? this.fieldData.value : '';
          this.textareaValue = val;
          if (e.type === 'richtext') {
            this.$refs.richEditor.resetContent(val);
          }
        }
        this.modalName = '';
        this.onBlur()
      },
      chooseMedia() {
        return new Promise(resolve => {
          uni.chooseMedia({
            count: 9,
            mediaType: ['image', 'video'],
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            camera: 'back',
            success(res) {
              console.log(res.type) // 文件类型，有效值有 image 、video、mix
              console.log(res.tempFiles) // 文件类型，有效值有 image 、video、mix
              resolve(res.tempFiles) // 数组 
            }
          })
        })
      },
      longpressNumEnd() {
        clearInterval(this.longpressTimer);
      },
      longpressNumChange(type) {
        if (type) {
          this.longpressTimer = setInterval(() => {
            this.numberChange(type);
          }, 100);
        }
      },
      numberChange(type) {
        if (this.fieldData.type === 'number' || this.fieldData.type === 'digit') {
          let step = this.fieldData.type === 'number' ? 1 : this.fieldData.type === 'digit' ? 0.5 : 0;
          if (this.fieldData.step) {
            step = this.fieldData.step;
          }
          if (!this.fieldData.value) {
            this.fieldData.value = this.fieldData.min ? this.fieldData.min : 0;
          }
          if (this.fieldData.max) {
            if (type === 'add') {
              if (this.fieldData.value + step <= this.fieldData.max) {
                this.fieldData.value = Number((this.fieldData.value + step).toFixed(1));
              } else {
                clearInterval(this.longpressTimer);
              }
            } else if (type === 'minus') {
              if (this.fieldData.value - step >= this.fieldData.min) {
                this.fieldData.value = Number((this.fieldData.value - step).toFixed(1));
              } else {
                clearInterval(this.longpressTimer);
              }
            }
          }
        }
        this.onBlur()
      },
      changeSlider(e) {
        this.fieldData.value = e.detail.value;
        this.onBlur()
      },
      previewImage(urls) {
        if (!urls) {
          return;
        }
        if (typeof urls === 'string') {
          urls = [urls];
        }
        urls = urls.map(url => {
          //若图片地址携带压缩图参数则预览时去掉此参数
          return url.replace(/&thumbnailType=fwsu_100/gi, '');
        });
        uni.previewImage({
          urls: urls,
          showmenu: false,
          // longPressActions: {
          //   itemList: ['发送给朋友', '保存图片', '收藏'],
          //   success: function(data) {
          //     console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
          //   }
          // }
        });
      },
      async getLocation() {
        // #ifdef MP-WEIXIN
        let settings = await new Promise(resolve => {
          uni.getSetting({
            success: (res) => {
              resolve(res)
            },
            fail: (err) => {
              resolve(err)
            }
          })
        })

        if (settings?.authSetting?. ['scope.userLocation'] === false) {
          uni.showModal({
            title: '提示',
            content: '未授权访问位置信息，请先在权限设置页面授权允许小程序访问您的位置信息',
            confirmText: '去设置',
            cancelText: '算了',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({

                })
              }
            }
          })
          return
        }
        // #endif
        if (this.pageType === 'detail') {
          if (this.fieldData.value) {
            let res = await this.getLocationFromSys()
            if (res.gcj_lat && res.gcj_lon) {
              uni.openLocation({
                longitude: res.gcj_lon,
                latitude: res.gcj_lat,
                success: function(res) {
                  // console.log('位置名称：' + res.name);
                  // console.log('详细地址：' + res.address);
                  // console.log('纬度：' + res.latitude);
                  // console.log('经度：' + res.longitude);
                }
              });

            }
          }
          return;
        }
        let self = this;
        const resData = await uni.chooseLocation()
        if (Array.isArray(resData) && resData.length > 1) {
          const res = resData[1]
          console.log('位置名称：' + res.name);
          console.log('详细地址：' + res.address);
          console.log('纬度：' + res.latitude);
          console.log('经度：' + res.longitude);
          if (self.fieldData.col_type === 'bxsys_obj_type_gps') {
            if (self.fieldData?.moreConfig?.scope) {
              let scope = self.fieldData?.moreConfig?.scope
              let {
                latitude: lat1,
                longitude: lng1
              } = await new Promise(resolve => {
                wx.getLocation({
                  type: 'gcj02',
                  success: function(res) {
                    resolve(res)
                  }
                })
              })
              if (lat1 && lng1) {
                let distance = this.calcDistance(lat1, lng1, res.latitude, res.longitude)
                if (!isNaN(Number(scope)) && !isNaN(distance) && distance > scope) {

                  uni.showModal({
                    title: '提示',
                    content: `所选位置不能距离当前定位超过${scope}米`,
                    showCancel: false,
                    success(res) {
                      if (res.confirm) {
                        uni.showToast({
                          title: `距离当前定位${distance}米`,
                          duration: 3000,
                          icon: 'none'
                        })
                      }
                    }
                  })
                  return
                }
              }
            }


            self.fieldData.value = await this.saveLocation(res)
            self.fkFieldLabel = res.address
          } else {
            self.fieldData.value = res.address + res.name;
          }
          self.$emit('chooseLocation', res);
          self.onBlur()
          self.getDefVal();
        }
      },
      calcDistance(lat1, lng1, lat2, lng2) {
        // 计算两个经纬度点之间的距离
        console.log(lat1, lng1, lat2, lng2)
        //进行经纬度转换为距离的计算
        function rad(d) {
          return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
        }
        const radLat1 = rad(lat1);
        const radLat2 = rad(lat2);
        const a = radLat1 - radLat2;
        const b = rad(lng1) - rad(lng2);
        let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        // 输出为公里
        // s = Math.round(s * 10000) / 10000;
        // // 输出为米
        s = Math.round(s * 1000);
        s = Number(s.toFixed(4));
        // uni.showToast({
        //   title: `距离打卡点:${Number(s)}米`,
        //   icon: 'none'
        // })
        return s
      },
      async getLocationFromSys() {
        const app = this.srvApp
        const req = {
          "serviceName": "srvsys_obj_type_gps_select",
          "colNames": ["*"],
          "condition": [{
            colName: 'gno',
            ruleType: 'eq',
            value: this.fieldData.value
          }],
          "page": {
            "pageNo": 1,
            "rownumber": 1
          }
        }
        const res = await this.$fetch('select', 'srvsys_obj_type_gps_select', req, app)
        if (res.success && res.data.length > 0) {
          return res.data[0]
        }
      },
      async saveLocation(e = {}) {
        let gno = ''
        if (this.fieldData.value) {
          let gnoData = await this.getLocationFromSys()
          gno = gnoData.gno
        }
        const app = this.srvApp
        let serviceName = 'srvsys_obj_type_gps_add'
        const req = [{
          serviceName: serviceName,
          data: [{
            addr_str: e.address + e.name,
            gcj_lat: e.latitude,
            gcj_lon: e.longitude
          }]
        }]
        if (gno) {
          serviceName = 'srvsys_obj_type_gps_update'
          req[0].serviceName = serviceName
          req[0].condition = [{
            colName: 'gno',
            ruleType: 'eq',
            value: gno
          }]
        }
        const res = await this.$fetch('operate', serviceName, req, app)
        if (res.success && res.data.length > 0) {

          this.fieldData.colData = res.data[0]
          return res.data[0].gno
        }

      },

      showModal(name) {
        this.modalName = name;

      },
      hideModal() {
        if (this.fieldData.value === '__others' && !this.otherNodeVal) {
          return
        }
        this.modalName = '';
      },
      async getFileList() {
        let fileDatas = await this.getFilePath(this.fieldData.value);
        let arr = []
        if (Array.isArray(fileDatas)) {
          for (let i = 0; i < fileDatas.length; i++) {
            const url =
              `${this.$api.getFilePath}${fileDatas[ i ].fileurl}&bx_auth_ticket=${uni.getStorageSync('bx_auth_ticket')}`;
            // `${self.$api.getFilePath}${fileDatas[ i ].fileurl}&bx_auth_ticket=${uni.getStorageSync('bx_auth_ticket')}&thumbnailType=fwsu_100`;

            arr.push({
              ...fileDatas[i],
              _fileurl: url
            });
          }
        }
        this.fileList = arr
      },
      async getDefVal() {
        let self = this;
        if (self.fieldData.type === 'FileList' && self.fieldData.value) {
          this.getFileList()
        } else if (self.fieldData.type === 'images' && self.fieldData.value) {
          if (self.fieldData.value.indexOf('http') === -1) {
            // 上传到系统的图片 只有图片编号 查到图片地址后再push
            let fileDatas = await self.getFilePath(self.fieldData.value);
            if (fileDatas) {
              self.imagesUrl = [];
              for (let i = 0; i < fileDatas.length; i++) {
                const url =
                  `${self.$api.getFilePath}${fileDatas[ i ].fileurl}&bx_auth_ticket=${uni.getStorageSync('bx_auth_ticket')}`;
                // `${self.$api.getFilePath}${fileDatas[ i ].fileurl}&bx_auth_ticket=${uni.getStorageSync('bx_auth_ticket')}&thumbnailType=fwsu_100`;
                self.imagesUrl.push(url);
              }
            }
          } else {
            // 网络地址 直接push
            self.imagesUrl = [];
            self.imagesUrl.push(self.fieldData.value);
          }
        } else if (self.fieldData.type === 'list' && self.fieldData.value !== '') {
          // 选项列表
          let listItemModel = self.fieldData.optionsConfig.model;
          let colKey = self.fieldData.optionsConfig.conditions;
          for (let i = 0; i < colKey.length; i++) {
            self.$set(self.listModel, colKey[i].colName, self.fieldModelsData[colKey[i].value]);
            self.listModel[colKey[i].colName] = self.fieldModelsData[colKey[i].value];
          }
        } else if (self.fieldData.type === 'Set' && self.fieldData.value && typeof self.fieldData.value ===
          'string') {
          // 多选
          self.fieldData.value = self.fieldData.value.split(',');
        } else if (self.fieldData && ['TreeSelector', 'Selector', 'location'].includes(self.fieldData.type)) {
          let cond = null;
          if (self.fieldData.type === 'TreeSelector') {
            // debugger
            // this.getTreeData()
          } else if (self.fieldData.value && self.fieldData?.option_list_v2?.refed_col && self.formType !==
            'add') {
            // cond = [{
            //   colName: self.fieldData.option_list_v2.refed_col,
            //   value: self.fieldData.value,
            //   ruleType: 'like'
            // }];
          }
          // if (self.fieldData.colData && self.fieldData.colData[self.fieldData.option_list_v2.refed_col] &&
          //   self.fieldData.colData[self.fieldData.option_list_v2.key_disp_col]) {
          //   self.fkFieldLabel = self.fieldData?.option_list_v2?.show_as_pair === true ?
          //     `${self.fieldData.colData[self.fieldData.option_list_v2.key_disp_col]}/${self.fieldData.colData[self.fieldData.option_list_v2.refed_col]}` :
          //     self.fieldData
          //     .colData[self.fieldData.option_list_v2.key_disp_col]

          // } else {

          self.getSelectorData(cond).then(_ => {
            if (self.fieldData.value) {
              let fkFieldLabel = self.selectorData.find(item => item.value === self.fieldData
                .value || item.value === Number(self.fieldData.value))
              if (fkFieldLabel && fkFieldLabel.label) {
                self.fkFieldLabel = fkFieldLabel.label
              } else if (self.fieldData.value) {
                self.fkFieldLabel = self.fieldData.value
              }
            }
            
            if (this.fieldData.value === '$firstRowData'||(this.fieldData.init_expr === '$firstRowData'&&!this.fieldData.value)) {
              if(this.formType === 'add'||(this.formType === 'update'&&this.formType === 'update')){
                if (this.fieldData.option_list_v2?.refed_col) {
                  this.fieldData.value = this.selectorData[0][this.fieldData.option_list_v2
                    .refed_col
                  ] || '';
                }
                this.fieldData['colData'] = this.selectorData[0];
                this.$emit('setColData', this.fieldData)
              }
            }
          });
          // }

        } else if (this.fieldData.type === 'MultiSelector') {
          this.getMultiSelectorOption()
        } else {
          let keys = Object.keys(this.fieldsModel)
          if (Array.isArray(keys) && keys.length > 0) {
            keys.forEach(key => {
              if (this.fieldData.column === key && !this.fieldData.value && this.fieldsModel[
                  key]) {
                this.fieldData.value = this.fieldsModel[key];
              }
            });
          }
        }
      },
      getMultiSelectorOption() {
        const srvInfo = this.fieldData?.srvInfo
        const url = `/${srvInfo.srv_app}/select/${srvInfo.service}`
        let req = {
          serviceName: srvInfo.service,
          colNames: srvInfo?.cols || ["*"],
          condition: [],
          page: {
            pageNo: 1,
            rownumber: 999,
          },
        };
        if (srvInfo.seq_col) {
          if (srvInfo.order_type) {
            req.order = [{
              colName: srvInfo.seq_col,
              orderType: srvInfo.order_type === "升序" ? "asc" : "desc",
            }, ];
          }
        }
        let fmtConditions = srvInfo.condition;
        if (Array.isArray(fmtConditions) && fmtConditions.length > 0) {
          for (let condition of fmtConditions) {
            let obj = {
              colName: condition.colName,
              ruleType: condition.ruleType,
              value: condition.value,
            };
            if (typeof condition.value === "object") {
              if (condition.value["value_type"] == "constant") {
                obj.value = condition.value["value"];
              } else if (condition.value["value_type"] == "sysvar") {
                if (condition.value["value"] == "nowdate") {
                  obj.value = this.dayjs().format("YYYY-MM-DD");
                } else {
                  // obj.value = eval("top." + condition.value["value"]);
                }
              } else if (condition.value["value_type"] == "mainData") {
                // 主表数据
                if (
                  this.mainData &&
                  typeof this.mainData === "object" &&
                  this.mainData[condition.value["value_key"]]
                ) {
                  obj.value =
                    this.mainData[condition.value["value_key"]] || null;
                }
              }
            }
            req.condition.push(obj);
          }
        }

        this.$http.post(url, req).then(res => {
          if (res?.data?.state == 'SUCCESS' && res.data.data.length > 0) {
            this.multiSelectorOptions = res.data.data.map(item => {
              return {
                text: item[srvInfo.disp_col],
                value: item[srvInfo.primary_col],
                is_selected: this.fieldData.value && this.fieldData.value.indexOf(item[srvInfo.primary_col]) > -
                  1 ? true : false
              }
            })
          }
        })
      },
      getFileInfo(e) {
        if (e.response.file_no) {
          this.fieldData.value = e.response.file_no;
        }
      },
      getImagesInfo(e) {
        let res = e.allImages[0];
        try {
          res = JSON.parse(e.allImages[0]);
        } catch (e) {
          //TODO handle the exception
        }
        this.fieldData.value = res.file_no;
        if (this.fieldData.value !== '' && this.fieldData.value !== null && this.fieldData.value !== undefined) {
          this.uploadFormData['file_no'] = this.fieldData.value;
          this.uploadFormData.table_name = this.fieldData.table_name;
        }
        // this.onBlur()
        this.getDefVal();
      },
      deleteImage(e) {
        console.log(e);
        this.fieldData.value = '';
      },
      confirmSelectTree(e) {
        if (e && e.id) {
          this.selectTreeData = e
          let srvInfo = this.fieldData.srvInfo || this.fieldData.option_list_v2;
          this.fkFieldLabel = srvInfo?.show_as_pair === true ?
            `${e[ srvInfo.key_disp_col ]}/${e[ srvInfo.refed_col ]}` : e[srvInfo.key_disp_col];
          this.fieldData['colData'] = e;
          this.$emit('setColData', this.fieldData)
          this.modalName = '';
        }
      },
      // 查找树型数据
      async getTreeData() {
        const srvInfo = this.fieldData?.option_list_v2
        this.treeMap.text = srvInfo.key_disp_col
        this.treeMap.value = srvInfo.column
        if (srvInfo?.serviceName) {
          const serviceName = srvInfo.serviceName;
          const appName = srvInfo.appNo || srvInfo.srv_app || this.srvApp;
          const parentCol = srvInfo?.parent_col || srvInfo?.parentCol
          let url = this.getServiceUrl(appName, serviceName, 'select');
          let condition = [];
          let fieldModelsData = this.deepClone(this.fieldsModel);
          if (srvInfo.isTree === false) {
            condition = [];
          } else {
            // if (this.curNode) {
            //   condition = [{
            //     colName: parentCol || 'parent_no',
            //     ruleType: 'eq',
            //     value: this.curNode
            //   }];
            // } else {
            if (Array.isArray(srvInfo?.conditions) &&
              srvInfo.conditions.length > 0) {
              condition = this.deepClone(srvInfo.conditions);
              condition = this.evalConditions(condition, fieldModelsData)
              condition = condition.map(item => {
                if (item.value && item.value.indexOf('data.') !== -1) {
                  let colName = item.value.slice(item.value.indexOf('data.') + 5);
                  if (fieldModelsData[colName]) {
                    item.value = fieldModelsData[colName];
                  }
                } else if (item.value && item.value.indexOf('top.user.user_no') !== -1) {
                  item.value = uni.getStorageSync('login_user_info').user_no;
                } else if (item.value && item.value.indexOf('globalData.') !== -1) {
                  let colName = item.value.slice(item.value.indexOf('globalData.') + 10);
                  if (globalData && globalData[colName]) {
                    item.value = globalData[colName];
                  }
                } else if (item.value && item.value.indexOf("'") === 0) {
                  item.value = item.value.replace(/\'/gi, '');
                }
                if (item.value_exp) {
                  delete item.value_exp;
                }
                return item;
              });
            } else {
              // condition = [{
              //   colName: parentCol || 'parent_no',
              //   ruleType: 'isnull'
              // }];
            }
            // }
          }

          // if ( this.fieldData.value && this.fieldData.option_list_v2?.refed_col) {
          //   condition = [{
          //     colName: this.fieldData.option_list_v2?.refed_col,
          //     ruleType: 'eq',
          //     value: this.fieldData.value
          //   }]
          // }

          let req = {
            serviceName: serviceName,
            colNames: ['*'],
            condition: condition,
            page: {
              // pageNo: this.page.pageNo,
              // rownumber: this.page.rownumber
            }
          };
          if (this.order) {
            req.order = this.order
          }
          const res = await this.$http.post(url, req);
          if (res && res.data && res.data.state === 'SUCCESS') {
            const nodeList = res.data.data;
            this.nodeList = res.data.data
            this.localTreedata = list2tree(nodeList)

            if (this.fieldData.value === '$firstRowData'||this.fieldData.init_expr === '$firstRowData') {
              if(this.formType === 'add'||(this.formType === 'update'&&this.formType === 'update')){
                if (this.fieldData.option_list_v2?.refed_col) {
                  this.fieldData.value = this.localTreedata[0][this.fieldData.option_list_v2
                    .refed_col
                  ] || '';
                }
                this.fieldData['colData'] = this.localTreedata[0];
                this.$emit('setColData', this.fieldData)
              }
            }
          }
        }
      },
      getCascaderValue(e) {
        if (e?.type == '自行输入') {
          this.fieldData.value = e.value || '';
          this.fkFieldLabel = e.value
        } else {
          let srvInfo = this.fieldData.srvInfo || this.fieldData.option_list_v2;
          if (e && srvInfo?.refed_col && e[srvInfo.refed_col]) {
            this.selectTreeData = e
            this.fkFieldLabel = srvInfo.show_as_pair === true ?
              `${e[ srvInfo.key_disp_col ]}/${e[ srvInfo.refed_col ]}` : e[srvInfo.key_disp_col];
            this.fieldData['colData'] = e;
            this.fieldData.value = e[srvInfo.refed_col];
            this.$emit('setColData', this.fieldData)
          }
        }
        this.hideModal();
      },
      searchFKDataWithKey(e) {
        this.treePageInfo.pageNo = 1
        if (e?.detail?.value) {
          let option = this.fieldData.option_list_v2;
          let relation_condition = {
            relation: 'OR',
            data: []
          };
          if (!option.key_disp_col && !option.refed_col) {
            return;
          }
          if (option.key_disp_col) {
            relation_condition.data.push({
              colName: option.key_disp_col,
              value: e.detail.value,
              ruleType: '[like]'
            })
          }
          if (option.refed_col) {
            relation_condition.data.push({
              colName: option.refed_col,
              value: e.detail.value,
              ruleType: '[like]'
            })
          }

          if (Array.isArray(this.field?.moreConfig?.searchCol) && this.field?.moreConfig?.searchCol.length > 0) {
            this.field?.moreConfig?.searchCol.forEach(col => {
              relation_condition.data.push({
                colName: col,
                value: e.detail.value,
                ruleType: '[like]'
              })
            })
          }

          if (Array.isArray(option.conditions) && option.conditions.length > 0) {
            let fieldModelsData = this.deepClone(this.fieldsModel);
            option.conditions = this.evalConditions(option.conditions, fieldModelsData)
            let data = this.deepClone(relation_condition.data)
            relation_condition = {
              relation: 'AND',
              data: [...option.conditions, {
                relation: 'OR',
                data: data
              }]
            }
          }
          this.getSelectorData(null, null, relation_condition);
        } else {
          this.getSelectorData();
        }
      },
      radioChange(e) {
        console.log('radioChange')
        this.getValid();
        this.fieldData.old_value = this.fieldData.value
        this.$emit('on-value-change', this.fieldData);
      },
      changeCheckbox(e) {
        if (e?.name) {
          this.setOptionList = this.setOptionList.map(item => {
            if (item.value === e.name) {
              item.checked = e.value
            }
            return item
          })
        }
      },
      pickerChange(e, type) {
        if (e?.type === '__others') {
          this.fieldData.value = e.value
          this.fkFieldLabel = e.value;
        } else if (this.fieldData.type === 'Selector') {
          this.fieldData.value = e
          let selectorData = this.radioOptions || this.selectorData
          let optionData = selectorData.find(item => item.value === e);
          if (optionData?.label) {
            this.fkFieldLabel = optionData.label;
            this.fieldData['colData'] = optionData;
          }
          this.otherNodeVal = ''
          // this.$emit('setColData', this.fieldData)
          // this.onBlur()
          this.hideModal()
        } else if (this.fieldData.type === 'Set') {
          if (Array.isArray(e)) {
            this.setOptionList = this.setOptionList.map(item => {
              if (e.includes(item.value)) {
                item.checked = true
              } else {
                item.checked = false
              }
              this.$set(item, 'checked', item.checked)
              return item
            })
            e = e.toString()
          }
          this.fieldData.value = e

        }
        if (type !== 'Selector') {
          this.hideModal();
        }
      },
      toFkAdd() {
        const option_list_v2 = this.fieldData?.option_list_v2
        if (option_list_v2?.serviceName) {
          let serviceName = option_list_v2.serviceName.replace('_select', '_add')
          let url = `/publicPages/formPage/formPage?serviceName=${serviceName}&type=add`
          if (option_list_v2.srv_app) {
            url += `&destApp=${option_list_v2.srv_app}`
          }
          uni.navigateTo({
            url
          })
        }

      },
      refresh() {
        this.treePageInfo.pageNo = 1
        this.getSelectorData('refresh')
      },
      nextPage() {
        this.treePageInfo.pageNo += 1
        this.getSelectorData()
      },
      async getSelectorData(cond, serv, relation_condition) {
        let self = this;
        serv = serv || self.fieldData?.option_list_v2?.serviceName
        // self.fieldData.old_value = self.fieldData.value
        if (this.fieldData.col_type === 'Enum') {
          if (Array.isArray(this.fieldData?.moreConfig?.customOptions) && this.fieldData?.moreConfig
            ?.customOptions
            .length > 0) {
            // 自定义枚举值
            this.selectorData = this.fieldData?.moreConfig?.customOptions
          }
          if (Array.isArray(this.fieldData.options)) {
            this.selectorData = this.fieldData.options;
          }
          return;
        }
        let req = {
          serviceName: serv,
          colNames: ['*'],
          condition: [],
          order: [],
          page: {
            pageNo: this.treePageInfo.pageNo,
            rownumber: this.treePageInfo.rownumber
          }
        };
        if (!req.serviceName) {
          return
        }

        let globalData = getApp().globalData
        let appName = self.fieldData?.option_list_v2?.srv_app || self.srvApp || uni.getStorageSync(
          'activeApp');
        let fieldModelsData = self.deepClone(self.fieldsModel);
        if (!self.procData.id) {
          fieldModelsData = self.deepClone(self.fieldsModel);
        } else {
          fieldModelsData = self.deepClone(self.procData);
        }
        // #ifdef H5
        top.user = uni.getStorageSync('login_user_info');
        // #endif
        if (cond && Array.isArray(cond)) {
          req.condition = cond;
        } else if (self.fieldData.option_list_v2 && Array.isArray(self.fieldData.option_list_v2.conditions) &&
          self.fieldData.option_list_v2.conditions.length > 0) {
          let condition = self.deepClone(self.fieldData.option_list_v2.conditions);
          condition = self.evalConditions(condition, fieldModelsData)
          condition = condition.map(item => {
            if (typeof item.value === 'string' && item.value) {
              if (item.value.indexOf('data.') !== -1) {
                let colName = item.value.slice(item.value.indexOf('data.') + 5);
                if (fieldModelsData[colName]) {
                  item.value = fieldModelsData[colName];
                }
              } else if (item.value.indexOf('top.user.user_no') !== -1) {
                item.value = uni.getStorageSync('login_user_info').user_no;
              } else if (item.value.indexOf('globalData.') !== -1) {
                let colName = item.value.slice(item.value.indexOf('globalData.') + 10);
                if (globalData && globalData[colName]) {
                  item.value = globalData[colName];
                }
              } else if (item.value.indexOf("'") === 0 && item.value.lastIndexOf(
                  "'") === item.value
                .length - 1) {
                item.value = item.value.replace(/\'/gi, '');
              }
            }
            if (item.value_exp) {
              delete item.value_exp;
            }
            return item;
          });
          if (Array.isArray(condition) && condition.length > 0) {
            req.condition = condition;
          } else {
            // return;
            // if(this.fieldData.value){
            // 	req.condition = [{
            // 		colName:this.fieldData.option_list_v2?.refed_col,
            // 		ruleType:'like',
            // 		value:this.fieldData.value
            // 	}]
            // }
          }
        }
        if (Array.isArray(req.condition) && Array.isArray(this.fieldData?.fk_condition)) {
          req.condition = [...req.condition, ...this.fieldData.fk_condition]
        }
        if (req.serviceName === 'srvsso_user_select') {
          if (Array.isArray(req.condition)) {} else {
            req.condition = [{
              colName: 'dept_no',
              ruleType: 'like',
              value: 'bx100sys'
            }];
          }
          appName = 'sso';
        }

        if (cond !== 'refresh' && this.fieldData?.disabled === true) {
          if (self.fieldData.value && self.fieldData.option_list_v2?.refed_col && !
            self
            .fieldData?.redundant) {
            if (Array.isArray(req.condition) !== true) {
              req.condition = []
            }
            req.condition.push({
              colName: self.fieldData.option_list_v2.refed_col,
              ruleType: 'eq',
              value: self.fieldData.value
            })
          }


          if (self.fieldData.value && self.fieldData?.option_list_v2?.refed_col && (!req.condition || req
              .condition
              .length == 0) && (self.fieldData.disabled ||
              self
              .fieldData.display == false)) {
            req.condition = [{
              colName: self.fieldData.option_list_v2.refed_col,
              ruleType: 'like',
              value: self.fieldData.value
            }]
          }

        }


        if (self.fieldData.option_list_v2?.relation_condition) {
          req.relation_condition = self.fieldData.option_list_v2?.relation_condition
          // delete req.condition;
        }


        if (relation_condition && typeof relation_condition === 'object') {
          req.relation_condition = relation_condition;
          // delete req.condition;
        }

        if (self.fieldData.option_list_v2?.relation_condition) {
          if (relation_condition) {
            req.relation_condition = {
              relation: "AND",
              data: [
                relation_condition,
                self.fieldData.option_list_v2?.relation_condition
              ]
            }
          } else {
            req.relation_condition = self.fieldData.option_list_v2?.relation_condition
          }
          // delete req.condition;
        }


        if (!req.serviceName) {
          return;
        }

        if (!appName) {
          return
        }


        let res = await self.onRequest('select', req.serviceName, req, appName);
        if (res.data.state === 'SUCCESS' && res.data.data.length > 0) {
          res.data.data = res.data.data.map(item => {
            const label = item[this.fieldData?.option_list_v2?.key_disp_col]
            if (label) {
              item.text = label
            }
            return item
          })
          if (res.data.page) {
            this.treePageInfo = res.data.page;
          }

          if (res.data.page && res.data.page.pageNo > 1) {
            let data = res.data.data;
            self.selectorData = [...self.selectorData, ...data];
          } else {
            self.selectorData = res.data.data;
          }

          if (this.fieldData.value === '$firstRowData' && this.formType == 'add') {
            if (self.selectorData.length > 0) {
              if (self.fieldData.option_list_v2?.refed_col) {
                self.fieldData.value = self.selectorData[0][self.fieldData.option_list_v2.refed_col] ||
                  '';
              }
              self.fieldData['colData'] = self.selectorData[0];
              self.$emit('setColData', self.fieldData)
            }
          }
          if (!this.fieldData.value && self.fieldData?.moreConfig?.defaultSelectCondition) {
            const defaultSelectCondition = self.fieldData?.moreConfig?.defaultSelectCondition
            if (Array.isArray(defaultSelectCondition) && defaultSelectCondition.length > 0) {
              let defaultSelecte = self.selectorData.find(item => {
                return defaultSelectCondition.every(cond => {
                  let val = this.renderStr(cond.value, {
                    ...this.globalVariable
                  })
                  if (cond?.ruleType == 'eq' && item[cond.colName] === val) {
                    return true
                  }
                })
              })

              if (defaultSelecte) {
                if (self.fieldData.option_list_v2?.refed_col) {
                  self.fieldData.value = defaultSelecte[self.fieldData.option_list_v2.refed_col] ||
                    '';
                }
                self.fieldData['colData'] = defaultSelecte;
                self.$emit('setColData', self.fieldData)
              }
            }
          }

          self.selectorData = self.selectorData.map(item => {
            const config = this.deepClone(this.fieldData.option_list_v2);
            // item.label = `${item[config.key_disp_col]||''}/${item[config.refed_col]||''}`
            item.label = config.show_as_pair === true ?
              `${item[ config.key_disp_col||'' ]}/${item[ config.refed_col ]}` : item[config
                .key_disp_col]
            // item.label = config.key_disp_col ? item[config.key_disp_col] : '';
            item.value = config.refed_col ? item[config.refed_col] : '';
            return item;
          });
          // }
          if (Array.isArray(self.selectorData) && self.selectorData.length > 0) {
            self.selectorData.forEach(item => {
              if (self.fieldData.option_list_v2 && (item[self.fieldData.option_list_v2
                    .refed_col] ===
                  self.fieldData.value || item[self.fieldData.option_list_v2.refed_col] ===
                  Number(self.fieldData.value)) && (self.fieldData.value || self.fieldData
                  .value === 0)) {
                self.fieldData['colData'] = item;
                self.$emit('setColData', self.fieldData)
              }
            });
          }

        } else if (res.data.state === 'SUCCESS' && res.data.data.length == 0) {
          if (res.data.page) {
            this.treePageInfo = res.data.page;
          }
          self.selectorData = []
        } else if (req.serviceName === 'srvsys_service_columnex_v2_select' && res.data && res.data.data &&
          Array.isArray(res.data.data.srv_cols)) {
          self.selectorData = res.data.data.srv_cols.map(item => {
            item.checked = false;
            return item;
          });
        }
      },
      confirmPicker(e) {
        let {
          start_col,
          end_col
        } = this.fieldData.moreConfig
        if (e?.start?.date && e?.end?.date && start_col && end_col) {
          this.fieldData.colData = {
            start: e?.start?.date,
            end: e?.end?.date
          }
          this.start = e.start.date
          this.end = e.end.date
          this.$emit('date-change', this.fieldData)
        }
      },
      bindTimeChange(e, type) {
        if (type && typeof type === 'string') {
          this.$set(this.fieldData, type, e.detail.value)
          // this.fieldData[type] = e.detail.value;
          if (!this.fieldData.value) {
            this.fieldData.value = [null, null]
          }
          if (type === 'startVal') {
            this.fieldData.value[0] = e.detail.value
          } else if (type === 'endVal') {
            this.fieldData.value[1] = e.detail.value
          }
        } else if (Array.isArray(e) && e.length > 0) {
          if (e.length === 2) {
            this.fieldData.value = e
          } else {
            this.fieldData.value = e
          }
        } else if (e && typeof e === 'object' && e.startDate && e.endDate) {
          if (!this.fieldData.value) {
            this.fieldData.value = [null, null]
          }
          this.fieldData.value[0] = e.startDate
          this.fieldData.value[1] = e.endDate
        } else if (e && typeof e === 'object' && e.startTime && e.endTime) {
          if (!this.fieldData.value) {
            this.fieldData.value = [null, null]
          }
          this.fieldData.value[0] = e.startTime
          this.fieldData.value[1] = e.endTime
        } else if (Array.isArray(e)) {
          // this.fieldData.value = e;
          debugger
        } else {
          this.fieldData.value = e.detail.value;
          if (this.fieldData?.moreConfig?.editor_type === 'date_time_linkage') {
            this.fieldData.colData = e.detail.time || {}
          }
          this.$emit('date-time-change', this.fieldData)
        }
        // this.$emit('on-value-change', this.fieldData);
      },
      openModal(type) {
        const self = this
        // 打开弹出层
        if (this.fieldData.disabled) {
          return
        }
        if (this.fieldData.type === 'Selector' && this.fieldData?.moreConfig?.editor_type ===
          'selectorList') {
          let option_list_v2 = self.fieldData.option_list_v2;
          if (Array.isArray(option_list_v2?.conditions)) {
            option_list_v2 = this.deepClone(option_list_v2)
            const fieldModelsData = this.fieldsModel
            let condition = this.deepClone(option_list_v2.conditions);
            condition = this.evalConditions(condition, fieldModelsData)
            condition = condition.map(item => {
              if (typeof item.value === 'string' && item.value) {
                if (item.value.indexOf('data.') !== -1) {
                  let colName = item.value.slice(item.value.indexOf('data.') + 5);
                  if (fieldModelsData[colName]) {
                    item.value = fieldModelsData[colName];
                  }
                } else if (item.value.indexOf('top.user.user_no') !== -1) {
                  item.value = uni.getStorageSync('login_user_info').user_no;
                } else if (item.value.indexOf('globalData.') !== -1) {
                  let colName = item.value.slice(item.value.indexOf('globalData.') + 10);
                  if (globalData && globalData[colName]) {
                    item.value = globalData[colName];
                  }
                } else if (item.value.indexOf("'") === 0 && item.value.lastIndexOf(
                    "'") === item.value
                  .length - 1) {
                  item.value = item.value.replace(/\'/gi, '');
                }
              }

              if (item.value_exp) {
                delete item.value_exp;
              }
              return item;
            });

            let url =
              `/publicPages/list2/list2?selectCol=${this.fieldData.column}&destApp=${option_list_v2.srv_app}&listType=selectorList&serviceName=${option_list_v2.serviceName}&cond=${JSON.stringify(condition)}`
            if (this.fieldData?.moreConfig?.listConfig && typeof this.fieldData?.moreConfig?.listConfig ===
              'object') {
              url += `&listConfig=${JSON.stringify(this.fieldData?.moreConfig?.listConfig)}`
            }

            if (this.fieldData?.moreConfig?.disabledCol) {
              url += `&disabledCol=${this.fieldData?.moreConfig?.disabledCol}`
            }

            let idCol = this.fieldData?.moreConfig?.option_id_col || this.fieldData.option_list_v2
              ?.refed_col || 'id'
            if (idCol) {
              url += `&idCol=${idCol}`
            }
            if (this.fieldData?.colData && this.fieldData.colData[idCol]) {
              url += `&selectedVal=${this.fieldData.colData[idCol]}`
            }
            const uuid = uni.$u.guid()
            this.selectorListUUID = uuid
            url += `&uuid=${uuid}`
            uni.$on('confirmSelect', (e) => {
              if (e.uuid === uuid) {
                const srvInfo = this.fieldData?.option_list_v2 || {}
                const refed_col = srvInfo?.refed_col
                const key_disp_col = srvInfo?.key_disp_col
                if (refed_col) {
                  // self.getCascaderValue(e.data)
                  this.fkFieldLabel = srvInfo.show_as_pair === true ?
                    `${e.data[ key_disp_col ]}/${e.data[ refed_col ]}` : e.data[
                      key_disp_col];
                  this.fieldData['colData'] = e.data;
                  this.fieldData.value = e.data[refed_col];
                  this.$nextTick(function() {
                    // this.$emit('setColData', this.fieldData)
                    uni.$off('confirmSelect')
                  })
                }
              }
            })
            uni.navigateTo({
              url: url
            })
          }
          return
        }
        let fieldData = this.deepClone(this.fieldData);
        switch (type) {
          case 'Set':
            if (Array.isArray(this.fieldData.option_list_v2)) {
              this.setOptionList = this.fieldData.option_list_v2.map(item => {
                if (this.fieldData.value && this.fieldData.value.includes(item.value)) {
                  item.checked = true;
                }
                return item;
              });
              this.modalName = 'MultiSelector';
            }
            break;
          case 'Selector':
            if (this.fieldData.col_type == 'Enum') {
              this.showEnumSelect = true
            } else {
              // this.getSelectorData(null, null, null)
              this.modalName = 'Selector';
              this.$refs?.optionSelector?.refresh()
            }
            break;
          case 'TreeSelector':
            // await this.getSelectorData(null, null, null)
            // this.modalName = 'TreeSelector';
            // this.selectTreeData = this.selectTreeData || {}
            break;
        }
      },
      onBlur(e) {
        // 输入框失去焦点 进行校验

        this.$nextTick(() => {
          this.$emit('on-value-change', this.fieldData);
          this.getValid();
        })
      },
      clearSelectValue() {
        this.fieldData.value = null
        this.$emit('on-value-change', this.fieldData);
        this.getValid();
      },
      selectItem(index, e) {
        if (index === -1) {
          return
        }
        const srvInfo = this.fieldData.srvInfo || this.fieldData.option_list_v2;
        // this.selectorData = e
        this.fkFieldLabel = srvInfo.show_as_pair === true ?
          `${e[ srvInfo.key_disp_col ]}/${e[ srvInfo.refed_col ]}` : e[srvInfo.key_disp_col];
        this.fieldData['colData'] = e;
        this.fieldData.value = e[srvInfo.refed_col];
        this.$emit('setColData', this.fieldData)
      },
      onSelectChange(e) {
        // this.getValid();
        // if (!e) {
        this.fieldData.value = e || ''
        // this.$emit('on-value-change', this.fieldData)
        // }
        // this.$emit('on-value-change', this.fieldData);
      },
      inputChange(e) {
        if (e?.detail?.value) {
          e.detail.value = e.detail.value.trim()
        }
        this.fieldData.value = e?.detail?.value || ''
        this.getValid();
        // this.onBlur()
      },
      getValid() {
        if (this.fieldData.display === false) {
          this.fieldData.valid = {
            valid: true,
            msg: '有效'
          };
          this.valid.valid = true;
          return this.valid
        }
        if (this.fieldData?.validators && this.fieldData.validators.indexOf('js_validate') !== -1) {
          let js_validate = this.fieldData.validators.slice(this.fieldData.validators.indexOf('js_validate'))
          if (js_validate) {
            let index = js_validate.indexOf("};")
            if (index !== -1) {
              js_validate = js_validate.slice(0, index + 1)
            }
          }
          const data = this.deepClone(this.mainData)
          data[this.fieldData.columns] = this.fieldData.value
          js_validate = eval(js_validate)
          let result = js_validate(data)
          if (result && typeof result === 'string') {
            // this.fieldData.value = null
            uni.showToast({
              title: result,
              icon: 'none'
            })
            this.fieldData.valid = {
              valid: false,
              msg: result
            };
            this.valid.valid = false
            this.valid.msg = result
            return this.valid
          }
          // let validate = await this.evalValidate(this.serviceName, column, fieldModel, this.appName)
        }

        if (this.fieldData.isRequire && this.fieldData.value) {
          if (this.fieldData.hasOwnProperty('_validators') && this.fieldData._validators.hasOwnProperty(
              'reg')) {
            // this.fieldData.valid = this.fieldData._validators.isType(this.fieldData.value);
            this.fieldData.valid = this.onRegTest(this.fieldData._validators?.reg, this.fieldData._validators
              ?.msg, this
              .fieldData.value);
            this.valid.valid = this.fieldData.valid?.valid ?? true;
            this.valid.msg = this.valid.msg || '不能为空';
          } else {
            this.fieldData.valid = {
              valid: true,
              msg: '有效'
            };
            this.valid.valid = true;
          }
        } else if (this.fieldData.isRequire && (this.fieldData.value === '' || this.fieldData.value === null ||
            this.fieldData.value === undefined)) {
          this.fieldData.valid = {
            display: this.fieldData.display,
            valid: false,
            msg: this.fieldData.label + '不能为空'
          };
          this.valid.valid = false;

        } else {
          this.fieldData.valid = {
            valid: true,
            msg: '有效'
          };
          this.valid.valid = true;
        }
        // this.$emit('on-value-change', this.fieldData);
        return this.valid;
      },
      initSetOptions() {
        this.$nextTick(function() {
          if (Array.isArray(this.fieldData.option_list_v2)) {
            this.setOptionList = this.fieldData.option_list_v2.map(item => {
              item.checked = false;
              if (this.fieldData.value && this.fieldData.value.includes(item.value)) {
                item.checked = true;
              }
              return item;
            });
          }
        });
      },
    },
    created() {
      if (this.field.type === 'DateRangeConfig') {
        this.start = this.fieldData.value;
        this.end = this.mainData[this.field?.moreConfig?.DateRangeConfig?.DateRangeEndColName]
      }
      let self = this;
      if (['images', 'media', 'RichText', 'FileList'].includes(this.fieldData.type)) {
        this.uploadFormData = {
          serviceName: 'srv_bxfile_service',
          interfaceName: 'add',
          app_no: '',
          table_name: '',
          columns: ''
        };
        this.uploadFormData.table_name = this.fieldData.table_name;
        this.uploadFormData['app_no'] = this.srvApp || this.fieldData?.srvInfo?.appNo || uni.getStorageSync(
          'activeApp');
        this.uploadFormData['columns'] = this.fieldData.column;
        if (this.fieldData.value !== '' && this.fieldData.value !== null && this.fieldData.value !== undefined) {
          this.uploadFormData['file_no'] = this.fieldData.value;
        }
        this.getDefVal();
      }
      if (this.pageType === 'detail' || this.pageType === 'update') {
        this.getDefVal();
      }
      this.initSetOptions()
      if (self.fieldData && ['Selector', 'TreeSelector', 'location', 'MultiSelector'].includes(self.fieldData.type)) {
        if (self.fieldData.type === 'TreeSelector') {
          this.getTreeData()
        } else {
          self.getDefVal()
        }
      }
      if (['TreeSelector'].includes(self.fieldData.type)) {
        if (!this.fieldData.value && this.fieldData?.moreConfig?.defaultSelectCondition) {
          // this.getSelectorData()
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import "./style.scss";

  @media screen and (min-width:800px) {
    .cu-btn {
      min-width: auto !important;
      max-width: 200px !important;
    }

    .dialog-button {
      .cu-btn {
        width: 200px;
        height: 40px;
        border-radius: 50px;
      }
    }

    .bottom-modal {
      &::before {
        vertical-align: middle;
      }

      .cu-dialog {
        max-width: $retail-dialog-width-base;
        border-radius: $retail-rounded-sm !important;
        overflow: hidden;
      }
    }
  }

  ::v-deep .selected-list {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
  }

  ::v-deep .uni-picker-container {
    z-index: 1999 !important;
  }

  ::v-deep .uni-picker-container.uni-time-select {
    z-index: 1999 !important;
  }
</style>
